<template>
	<view>
		<!--视频播放组件-->
		<video-player 
			:visible="showVideoPlayer" 
			:videoUrl="currentVideoUrl"
			@update:visible="showVideoPlayer = $event"
			@close="onVideoClose">
		</video-player>
		
		<!--标题栏-->
		<bar-title bgColor="bg-white" isBack>
			<block slot="content">
				<text class="margin-right-xs">仔仔</text>
				<text class="cu-tag bg-blue sm radius">
					<text class="cuIcon-male" />
				</text>
			</block>
			<block slot="right">
				<text class="cuIcon-more" />
			</block>
		</bar-title>

		<!--商品信息-->
		<view class="bg-white zaiui-goods-details-box pay_status">
			<view class="cu-avatar radius" :style="[{ backgroundImage: 'url(' + goods_img + ')' }]" />
			<view class="goods-info-view">
				<view class="title-view">
					<view class="text-cut text-black">商品名称 99新 苹果 iPhoneX 256G 银色</view>
					<text class="text-right text-gray text-sm">交易成功</text>
				</view>
				<view class="price-tools-view">
					<text class="text-price text-red text-lg">2999.00</text>
					<view class="zaiui-tag-view">
						<text class="cu-tag bg-red radius sm">马上买</text>
						<text class="cu-tag line-black radius sm">钱款去向</text>
						<text class="cu-tag line-black radius sm">
							<text class="cuIcon-more" />
						</text>
					</view>
				</view>
			</view>

			<!--提示-->
			<view class="zaiui-goods-tip-view" :class="tipShow ? 'show' : ''">
				<text class="text-black cuIcon-notification icon" />
				<view class="text-sm content">
					<text class="text-black">平台绝对不会收取实名认证等任何费用。让你加微信支付或者点链接、扫二维码的都是骗子！</text>
					<text class="text-blue">查看骗术></text>
				</view>
			</view>

			<!--按钮-->
			<view class="zaiui-goods-info-btn-view" @tap="tipShowTap">
				<view class="h-line-view">
					<view class="h-line" />
					<view class="h-line" />
				</view>
			</view>
		</view>

		<!--聊天框-->
		<view class="zaiui-chat-scroll-view" :class="chatShow ? 'tools' : ''" @tap="setToolsHidden">
			<scroll-view scroll-into-view="lastMessage" scroll-y class="scroll-view" @scroll="chatScroll"
				:scroll-top="scroll_top">
				<!--连接状态提示-->
				<view v-if="!isConnected" class="news-view-item notice">
					<view class="bg-white notice-content-view">
						<view class="cu-avatar round" style="background-image:url(/static/images/news/abb.png);" />
						<view class="notice-content">
							<view class="text-black">连接中...</view>
							<view class="text-gray text-sm introduce">正在连接到聊天服务器</view>
						</view>
					</view>
				</view>

				<!--消息列表-->
				<view v-for="(message, index) in messageList" :key="message.id || index"
					:id="message.id || 'message_' + index" class="news-view-item"
					:class="message.isSelf ? 'right' : 'left'">

					<!--对方消息-->
					<template v-if="!message.isSelf">
						<view class="cu-avatar round" :style="{ backgroundImage: 'url(' + message.avatar + ')' }" />
						<view class="news-content">
							<view class="bg-white text-black content">
								<text v-if="message.status === 'sending'" class="text-sm text-gray status">发送中</text>
								<text v-if="message.status === 'fail'" class="text-sm text-red status">发送失败</text>
								<view v-if="message.type === 'image' || message.type === 'TIMImageElem'">
									<image v-if="message.imageUrl" class="chat-image" :src="message.imageUrl"
										mode="widthFix" @tap="previewImage(message.imageUrl)" />
								</view>
								<view v-else-if="message.type === 'video' || message.type === 'TIMVideoFileElem'" class="chat-video" @tap="playVideo(message.videoUrl)">
									<view class="video-preview">
										<view class="video-overlay">
											<view class="video-play-icon">
												<text class="cuIcon-playfill text-white" />
											</view>
											<text class="video-duration" v-if="message.duration">{{ formatVideoDuration(message.duration) }}</text>
										</view>
									</view>
								</view>
								<text v-else>{{ message.content }}</text>
								<image v-if="message.emoji" class="emoji" :src="message.emoji" mode="widthFix" />
							</view>
						</view>
					</template>

					<!--我的消息-->
					<template v-else>
						<view class="news-content">
							<view class="bg-blue content">
								<text v-if="message.status === 'sending'" class="text-sm text-gray status">发送中</text>
								<text v-if="message.status === 'fail'" class="text-sm text-red status">发送失败</text>
								<text v-if="message.status === 'success'" class="text-sm text-gray status">已读</text>
								<text v-if="message.status === 'unread'" class="text-sm text-blue status">未读</text>
								<view v-if="message.type === 'image' || message.type === 'TIMImageElem'">
									<image v-if="message.imageUrl" class="chat-image" :src="message.imageUrl"
										mode="widthFix" @tap="previewImage(message.imageUrl)" />
								</view>
								<view v-else-if="message.type === 'video' || message.type === 'TIMVideoFileElem'" class="chat-video" @tap="playVideo(message.videoUrl)">
									<view class="video-preview">
										<view class="video-overlay">
											<view class="video-play-icon">
												<text class="cuIcon-playfill text-white" />
											</view>
											<text class="video-duration" v-if="message.duration">{{ formatVideoDuration(message.duration) }}</text>
										</view>
									</view>
								</view>
								<text v-else>{{ message.content }}</text>
								<image v-if="message.emoji" class="emoji" :src="message.emoji" mode="widthFix" />
							</view>
						</view>
						<view class="cu-avatar round" :style="{ backgroundImage: 'url(' + message.avatar + ')' }" />
					</template>
				</view>

				<!--时间分隔-->
				<view v-if="showTimeSeparator" class="news-view-item time">
					<text class="text-sm text-gray">{{ currentTime }}</text>
				</view>

				<!--滚动到最新消息的锚点-->
				<view id="lastMessage" />
			</scroll-view>
		</view>

		<!--底部区域-->
		<view class="bg-white zaiui-footer-fixed zaiui-foot-padding-bottom">
			<!--操作区域-->
			<view class="cu-bar input zaiui-foot-bar-input-tools">
				<view class="action">
					<text class="cuIcon-rounddown text-gray" @tap="speedyTap" />
				</view>
				<input class="input-radius" placeholder="输入聊天内容" v-model="inputMessage" @confirm="sendMessage" />
				<view class="action">
					<text class="cuIcon-emoji text-gray" @tap="emojiTap" />
				</view>
				<view class="action">
					<text class="cuIcon-roundaddfill text-red" @tap="toolsTap" />
				</view>
			</view>

			<!--快捷输入-->
			<view class="zaiui-speedy-view" :class="speedyShow ? 'show' : ''">
				<view class="key-bar text-center" @tap="quickSend('走平台，支持平台验机吗？')">走平台，支持平台验机吗？</view>
				<view class="key-bar text-center" @tap="quickSend('能便宜一点吗？')">能便宜一点吗？</view>
				<view class="key-bar text-center" @tap="quickSend('是否包邮？')">是否包邮？</view>
				<view class="key-bar text-center" @tap="quickSend('机器有发票吗？')">机器有发票吗？</view>
				<view class="key-bar text-center" @tap="quickSend('机器配件都在吗？')">机器配件都在吗？</view>
				<view class="key-bar text-center" @tap="quickSend('能发个视频或图片吗？')">能发个视频或图片吗？</view>
			</view>

			<!--表情栏-->
			<view class="zaiui-emoji-view" :class="emojiShow ? 'show' : ''">
				<view class="emoji-scroll-view-box">
					<swiper class="emoji-swiper" :current="emoji_swiper" indicator-dots @change="emoji_change">
						<swiper-item>
							<view class="cu-list grid no-border">
								<block v-for="(item, index) in emojiNum" :key="index" v-if="index < 20">
									<image class="emoji" :src="getEmojiUrl(index)" mode="widthFix"
										@tap="emojiSelectTap(index)" />
								</block>
								<image class="del_btn" src="/static/zaiui/img/aa2.png" mode="widthFix"
									@tap="emojiDelTap" />
							</view>
						</swiper-item>
						<swiper-item>
							<view class="cu-list grid no-border">
								<block v-for="(item, index) in emojiNum" :key="index" v-if="index >= 20 && index < 40">
									<image class="emoji" :src="getEmojiUrl(index)" mode="widthFix"
										@tap="emojiSelectTap(index)" />
								</block>
								<image class="del_btn" src="/static/zaiui/img/aa2.png" mode="widthFix"
									@tap="emojiDelTap" />
							</view>
						</swiper-item>
					</swiper>
				</view>
				<!--选择表情类型栏-->
				<scroll-view class="emoji-tools-scroll-view" scroll-x>
					<view id="emoji_tools1" class="emoji-tools-item" :class="emojiUrl == 'emoji' ? 'select' : ''"
						@tap="emoji_tools_tap('emoji')">
						<image class="emoji" src="/static/images/emoji/1.png" mode="widthFix" />
					</view>
					<view id="emoji_tools2" class="emoji-tools-item" :class="emojiUrl == 'emoji_1' ? 'select' : ''"
						@tap="emoji_tools_tap('emoji_1')">
						<image class="emoji" src="/static/images/emoji_1/1.png" mode="widthFix" />
					</view>
				</scroll-view>
			</view>

			<!--更多工具-->
			<view class="zaiui-tools-view" :class="toolsShow ? 'show' : ''">
				<view class="cu-list grid col-4 no-border">
					<view class="cu-item" @tap="takePhoto">
						<view class="img-view">
							<image class="img" src="/static/images/news/az2.png" mode="widthFix" />
						</view>
						<text>拍照</text>
					</view>
					<view class="cu-item" @tap="chooseImage">
						<view class="img-view">
							<image class="img" src="/static/images/news/ayy.png" mode="widthFix" />
						</view>
						<text>相册</text>
					</view>
					<!-- <view class="cu-item">
						<view class="img-view">
							<image class="img" src="/static/images/news/azf.png" mode="widthFix" />
						</view>
						<text>语音通话</text>
					</view> -->
					<view class="cu-item" @tap="chooseVideo">
						<view class="img-view">
							<image class="img" src="/static/images/news/aze.png" mode="widthFix" />
						</view>
						<text>视频</text>
					</view>
					<view class="cu-item">
						<view class="img-view">
							<image class="img" src="/static/images/news/az4.png" mode="widthFix" />
						</view>
						<text>位置</text>
					</view>
					<view class="cu-item">
						<view class="img-view">
							<image class="img" src="/static/images/news/az3.png" mode="widthFix" />
						</view>
						<text>宝贝</text>
					</view>
					<view class="cu-item">
						<view class="img-view">
							<image class="img" src="/static/images/news/azg.png" mode="widthFix" />
						</view>
						<text>联系卡</text>
					</view>
				</view>
			</view>

		</view>

	</view>
</template>

<script>
import barTitle from '@/components/basics/bar-title';
import tools from '@/utils/tools.js'
import TIMManager from '@/utils/tim-manager.js'
import VideoPlayer from '@/components/video-player.vue'

export default {
	components: {
		barTitle,
		VideoPlayer
	},
	data() {
		return {
			// 腾讯云IM相关
			isConnected: false,
			messageList: [],
			inputMessage: '',
			chatUserName: '对方昵称',

			// 原有数据
			goods_img: '/static/images/goods/1.jpg',
			tipShow: false,
			chatShow: false,
			speedyShow: false,
			emojiShow: false,
			toolsShow: false,
			emoji_swiper: 0,
			emojiUrl: 'emoji',
			emojiNum: 40,
			scroll_top: 0,
			showTimeSeparator: false,
			currentTime: '',
			
			// 视频播放相关
			showVideoPlayer: false,
			currentVideoUrl: ''
		}
	},

	async onLoad(options) {
		// 设置对方用户信息
		this.chatUserName = options.targetUserName || '对方昵称'

		try {
			// 尝试使用真实聊天功能
			await this.initRealChat(options)

		} catch (error) {
			console.error('真实聊天初始化失败，使用模拟模式:', error)
		}
	},

	onUnload() {
		// 页面卸载时登出
		TIMManager.logout()
	},

	methods: {
		// 初始化真实聊天
		async initRealChat(options) {
			try {

				// 获取当前用户ID和对方用户ID（这里使用模拟数据，实际项目应该从用户系统获取）
				const currentUserId = 'user_020'; // 当前用户ID
				const targetUserId = 'user_001';   // 对方用户ID
				// 获取登录信息
				const loginInfo = await this.getLoginInfo(currentUserId, targetUserId);
				if (loginInfo) {
					// 初始化腾讯云IM
					const timInitResult = await TIMManager.init();

					// 设置会话
					TIMManager.setConversation(targetUserId);
					// 登录腾讯云IM
					const loginResult = await TIMManager.login(loginInfo.userId, loginInfo.userSig);

					if (!loginResult.success) {
						throw new Error('腾讯云IM登录失败: ' + loginResult.code);
					}

					console.log('腾讯云IM登录成功');

					// 设置事件监听
					this.setupEventListeners();

					// 加载历史消息
					await this.loadHistoryMessages();

					this.isConnected = true;
				}

			} catch (error) {
				console.error('初始化真实聊天失败:', error);
				throw error;
			}
		},

		// 从后端API获取登录信息
		async getLoginInfo(currentUserId, targetUserId) {
			try {
				// 先自动注册对方用户（如果尚未注册）
				await this.$http.post(`http://localhost:3000/api/chat/register-user`, {
					userId: targetUserId,
					nickname: '仔仔'
				});

				// 再获取登录信息
				const response = await this.$http.post(`http://localhost:3000/api/chat/login-info`, {
					currentUserId,
					targetUserId
				});

				// 确保会话ID格式正确
				if (response.data && response.data.conversationId) {
					// 正确的会话ID格式应该是：C2C + 目标用户ID
					const correctConversationId = `C2C${targetUserId}`;
					response.data.conversationId = correctConversationId;
				}
				
				return response.data;

			} catch (error) {
				console.error('获取登录信息失败:', error);
			}
		},

		// 设置事件监听
		setupEventListeners() {
			try {
				// 监听连接状态变化
				TIMManager.on('onConnectionStateChanged', (state) => {
					console.log('连接状态:', state)
					this.isConnected = state.state === 'CONNECTED'
				})

				// 监听新消息
				TIMManager.on('onMessageReceived', (message) => {
					this.handleNewMessage(message)
				})

				// 监听消息已读回执
				TIMManager.on('onMessageRead', (readReceiptInfo) => {
					console.log('消息已读:', readReceiptInfo)
				})

				console.log('事件监听器设置成功')
			} catch (error) {
				console.error('设置事件监听器失败:', error)
			}
		},

		// 加载历史消息
		async loadHistoryMessages() {
			try {
				// 等待 SDK ready 状态
				await TIMManager.waitForSDKReady(10000);
				console.log('SDK ready，开始加载历史消息');

				const messages = await TIMManager.getHistoryMessages()
				this.messageList = messages.map(msg => this.formatMessage(msg))
				this.scrollToBottom()
				console.log('历史消息加载成功，消息数量:', messages.length);
			} catch (error) {
				console.error('加载历史消息失败:', error)
				// 如果等待 SDK ready 超时，使用模拟数据
				if (error.message.includes('等待 SDK ready 超时')) {
					console.log('SDK ready 超时，使用模拟数据');
				}
			}
		},

		// 处理新消息
		handleNewMessage(message) {
			const formattedMessage = this.formatMessage(message)
			this.messageList.push(formattedMessage)
			this.scrollToBottom()

			// 显示时间分隔符
			this.showTimeSeparator = true
			this.currentTime = this.formatTime(new Date())

			// 如果是我发送的消息，触发自动回复
			if (message.isSelf) {
				this.triggerAutoReply(message.content)
			}
		},

		// 更新消息状态
		updateMessageStatus(messageId, status) {
			const index = this.messageList.findIndex(msg => msg.id === messageId)
			if (index !== -1) {
				this.messageList[index].status = status
				this.$forceUpdate()
			}
		},

		// 格式化消息
		formatMessage(message) {
			return {
				id: message.id || 'msg_' + Date.now() + Math.random(),
				content: message.content || '',
				isSelf: message.isSelf || false,
				avatar: message.avatar || '/static/images/avatar/1.jpg',
				status: message.status || 'success',
				emoji: message.emoji || null,
				time: message.time || new Date()
			}
		},

		// 发送消息
		async sendMessage() {
			if (!this.inputMessage.trim()) return
			try {
				// 创建临时消息（显示发送中状态）
				const tempMessage = {
					id: 'temp_' + Date.now(),
					content: this.inputMessage,
					isSelf: true,
					avatar: '/static/images/avatar/2.jpg',
					status: 'sending'
				}

				this.messageList.push(tempMessage)
				this.scrollToBottom()

				// 发送消息到腾讯云IM
				const sendResult = await TIMManager.sendTextMessage(this.inputMessage)

				// 更新消息状态
				const index = this.messageList.findIndex(msg => msg.id === tempMessage.id)
				if (index !== -1) {
					if (sendResult.success) {
						this.messageList[index].id = sendResult.message?.ID || sendResult.message?.id || tempMessage.id
						this.messageList[index].status = 'unread'
					} else {
						this.messageList[index].status = 'fail'

						// 显示具体的错误信息
						if (sendResult.code === 20003 || sendResult.error?.includes('用户未注册')) {
							// 显示用户友好的提示
							uni.showToast({
								title: '对方用户未注册，无法发送消息',
								icon: 'none',
								duration: 3000
							});
						} else if (sendResult.code === 20004) {
							uni.showToast({
								title: '登录状态异常，请重新登录',
								icon: 'none',
								duration: 3000
							});
						}
					}
				}

				// 清空输入框
				this.inputMessage = ''

			} catch (error) {
				console.error('发送消息失败:', error)
				// 更新消息状态为发送失败
				const index = this.messageList.findIndex(msg => msg.id && msg.id.startsWith('temp_'))
				if (index !== -1) {
					this.messageList[index].status = 'fail'
				}

				// 显示错误提示
				if (error.message && error.message.includes('Invalid sender or receiver identifier')) {
					uni.showToast({
						title: '对方用户未注册，无法发送消息',
						icon: 'none',
						duration: 3000
					});
				}
			}
		},

		// 快捷发送
		quickSend(content) {
			this.inputMessage = content
			this.sendMessage()
		},

		// 滚动到底部
		scrollToBottom() {
			this.$nextTick(() => {
				this.scroll_top = 999999
				setTimeout(() => {
					this.scroll_top = 0
				}, 100)
			})
		},

		// 格式化时间
		formatTime(date) {
			return tools.formatTime(date, 'HH:mm')
		},

		// 触发自动回复
		triggerAutoReply(messageContent) {
			// 延迟2-5秒后回复，模拟真实对话
			const delay = Math.random() * 3000 + 2000; // 2-5秒随机延迟

			setTimeout(() => {
				const replyMessage = this.generateAutoReply(messageContent);

				// 添加自动回复消息
				this.messageList.push({
					id: 'auto_reply_' + Date.now(),
					content: replyMessage,
					isSelf: false,
					avatar: '/static/images/avatar/1.jpg',
					status: 'success',
					time: new Date()
				});

				this.scrollToBottom();
			}, delay);
		},

		// 生成智能自动回复
		generateAutoReply(messageContent) {
			// 商品咨询相关关键词
			const keywords = {
				price: ['便宜', '价格', '多少钱', '价位', '优惠', '打折'],
				stock: ['还有吗', '在吗', '库存', '有没有', '可买'],
				shipping: ['包邮', '运费', '快递', '送货', '发货'],
				quality: ['质量', '成色', '新旧', '正品', '真假', '发票', '保修'],
				inspection: ['验机', '检查', '检测', '平台', '保证'],
				meeting: ['见面', '线下', '当面', '自提', '交易'],
				other: ['你好', '在吗', '咨询', '请问', '问一下']
			};

			// 检查消息内容中的关键词
			const content = messageContent.toLowerCase();

			// 价格相关回复
			if (keywords.price.some(keyword => content.includes(keyword))) {
				const priceReplies = [
					'已经是最优惠价格了，转转平台保证正品质量',
					'价格已经很实惠了，支持验机服务，保证商品质量',
					'这个价格包含平台验机服务，保证机器没有任何问题'
				];
				return priceReplies[Math.floor(Math.random() * priceReplies.length)];
			}

			// 库存相关回复
			if (keywords.stock.some(keyword => content.includes(keyword))) {
				const stockReplies = [
					'商品还在的，欢迎咨询购买',
					'库存充足，可以随时下单',
					'还有现货，支持随时交易'
				];
				return stockReplies[Math.floor(Math.random() * stockReplies.length)];
			}

			// 运费相关回复
			if (keywords.shipping.some(keyword => content.includes(keyword))) {
				const shippingReplies = [
					'全国包邮，顺丰快递发货',
					'下单后24小时内发货，顺丰包邮',
					'支持包邮，江浙沪地区次日达，其他地区2-3天'
				];
				return shippingReplies[Math.floor(Math.random() * shippingReplies.length)];
			}

			// 质量相关回复
			if (keywords.quality.some(keyword => content.includes(keyword))) {
				const qualityReplies = [
					'99新机器，外观无划痕，功能一切正常',
					'支持转转平台验机，保证正品质量',
					'机器有原装发票，还在保修期内'
				];
				return qualityReplies[Math.floor(Math.random() * qualityReplies.length)];
			}

			// 验机相关回复
			if (keywords.inspection.some(keyword => content.includes(keyword))) {
				const inspectionReplies = [
					'支持转转平台验机服务，确保商品质量',
					'走平台验机更放心，专业检测团队把关',
					'平台验机包括外观、功能、电池等全面检测'
				];
				return inspectionReplies[Math.floor(Math.random() * inspectionReplies.length)];
			}

			// 见面交易相关回复
			if (keywords.meeting.some(keyword => content.includes(keyword))) {
				const meetingReplies = [
					'建议走转转平台交易，安全有保障',
					'平台交易更安全，支持验机和退货保障',
					'线下交易风险较大，建议使用平台担保交易'
				];
				return meetingReplies[Math.floor(Math.random() * meetingReplies.length)];
			}

			// 其他问候或咨询
			if (keywords.other.some(keyword => content.includes(keyword))) {
				const otherReplies = [
					'您好，有什么可以帮您的吗？',
					'欢迎咨询，商品详细信息和图片可以参考商品页面',
					'很高兴为您服务，商品支持转转平台验机'
				];
				return otherReplies[Math.floor(Math.random() * otherReplies.length)];
			}

			// 默认回复
			const defaultReplies = [
				'收到您的消息，我会尽快回复您',
				'感谢您的咨询，商品支持转转平台验机服务',
				'有什么其他问题可以随时问我',
				'欢迎咨询，商品详细信息可以参考商品页面'
			];

			return defaultReplies[Math.floor(Math.random() * defaultReplies.length)];
		},

		// 原有方法
		tipShowTap() {
			this.tipShow = !this.tipShow
		},

		setToolsHidden() {
			this.chatShow = false
			this.speedyShow = false
			this.emojiShow = false
			this.toolsShow = false
		},

		chatScroll(e) {
			// 滚动处理
		},

		speedyTap() {
			this.speedyShow = !this.speedyShow
			this.emojiShow = false
			this.toolsShow = false
			this.chatShow = this.speedyShow
		},

		emojiTap() {
			this.emojiShow = !this.emojiShow
			this.speedyShow = false
			this.toolsShow = false
			this.chatShow = this.emojiShow
		},

		toolsTap() {
			this.toolsShow = !this.toolsShow
			this.speedyShow = false
			this.emojiShow = false
			this.chatShow = this.toolsShow
		},

		getEmojiUrl(index) {
			return `/static/images/${this.emojiUrl}/${index + 1}.png`
		},

		emojiSelectTap(index) {
			const emojiUrl = this.getEmojiUrl(index)
			this.inputMessage += `[表情${index + 1}]`
		},

		emojiDelTap() {
			if (this.inputMessage.length > 0) {
				this.inputMessage = this.inputMessage.slice(0, -1)
			}
		},

		emoji_change(e) {
			this.emoji_swiper = e.detail.current
		},

		emoji_tools_tap(type) {
			this.emojiUrl = type
		},

		// 拍照发送图片
		takePhoto() {
			const that = this;
			uni.chooseImage({
				count: 1,
				sourceType: ['camera'],
				sizeType: ['compressed'],
				success: function (res) {
					that.sendImageMessage(res);
				},
				fail: function (error) {
					console.error('拍照失败:', error);
					uni.showToast({
						title: '拍照失败',
						icon: 'none'
					});
				}
			});
		},

		// 选择相册图片
		chooseImage() {
			const that = this;
			uni.chooseImage({
				count: 1,
				sizeType: ['original', 'compressed'], // 可以指定是原图还是压缩图，默认二者都有
				sourceType: ['album'], // 从相册选择
				success: function (res) {
					that.sendImageMessage(res);
				},
				fail: function (error) {
					console.error('选择图片失败:', error);
					uni.showToast({
						title: '选择图片失败',
						icon: 'none'
					});
				}
			});
		},
		chooseVideo(){
			const that = this;
			uni.chooseVideo({
				sourceType: ['album', 'camera'], // 来源相册或者拍摄
				maxDuration: 200, // 设置最长时间200s
				camera: 'back', // 后置摄像头
				success: function (res) {
					that.sendVideoMessage(res);
				},
				fail: function (error) {
					console.error('选择视频失败:', error);
					uni.showToast({
						title: '选择视频失败',
						icon: 'none'
					});
				}
			});
		},
		// 发送图片消息
		async sendImageMessage(imagePath) {
			try {

				// 先创建本地消息，显示发送中状态
				const localMessage = {
					id: 'img_' + Date.now(),
					content: '',
					imageUrl: imagePath.tempFilePaths[0],
					type: 'image',
					isSelf: true,
					avatar: '',
					status: 'sending',
					time: new Date()
				};

				this.messageList.push(localMessage);
				this.scrollToBottom();

				// 通过TIM管理器发送图片
				const result = await TIMManager.sendImageMessage(imagePath);

				if (result.success) {
					// 更新消息状态为成功
					localMessage.status = 'success';
					localMessage.id = result.message.ID; // 使用服务器返回的ID
					// 如果是图片消息，获取图片URL
					if (result.message.type === 'TIMImageElem') {
						const imageInfo = result.message.payload.imageInfoArray[0];
						//返回值为imageInfo.imageUrl
						if (imageInfo) {
							// localMessage.imageUrl = imageInfo.imageUrl || imagePath;
						}
					}

					console.log('图片发送成功');
				} else {
					// 发送失败
					localMessage.status = 'fail';
					console.error('图片发送失败:', result.error);
					uni.showToast({
						title: '图片发送失败',
						icon: 'none'
					});
				}

				// 更新消息列表
				this.$forceUpdate();

			} catch (error) {
				console.error('发送图片消息异常:', error);
				uni.showToast({
					title: '发送失败',
					icon: 'none'
				});
			}
		},
		// 发送视频消息
		async sendVideoMessage(videoFile) {
			try {
				console.log(videoFile.tempFilePath)
				// 先创建本地消息，显示发送中状态
				const localMessage = {
					id: 'video_' + Date.now(),
					content: '[视频]',
					videoUrl: videoFile.tempFilePath,
					type: 'video',
					isSelf: true,
					avatar: '/static/images/avatar/2.jpg',
					status: 'sending',
					time: new Date()
				};

				this.messageList.push(localMessage);
				this.scrollToBottom();
				/*
				// 通过TIM管理器发送视频
				const result = await TIMManager.sendVideoMessage(videoFile);
				if (result.success) {
					// 更新消息状态为成功
					localMessage.status = 'success';
					localMessage.id = result.message.ID || result.message.id || localMessage.id;

					// 如果是视频消息，获取视频URL
					if (result.message.type === 'TIMVideoFileElem') {
						const videoInfo = result.message.payload;
						if (videoInfo && videoInfo.remoteVideoUrl) {
							localMessage.videoUrl = videoInfo.remoteVideoUrl;
						}
					}
					console.log('视频发送成功');
				} else {
					// 发送失败
					localMessage.status = 'fail';
					console.error('视频发送失败:', result.error);
					uni.showToast({
						title: '视频发送失败',
						icon: 'none'
					});
				}
				*/
				// 更新消息列表
				this.$forceUpdate();

			} catch (error) {
				console.error('发送视频消息异常:', error);
				uni.showToast({
					title: '发送失败',
					icon: 'none'
				});
			}
		},
		// 预览图片
		previewImage(url) {
			if (!url) return;

			uni.previewImage({
				urls: [url],
				showmenu: true
			});
		},

		// 获取视频缩略图
		getVideoThumbnail(message) {
			// 如果有缩略图URL，优先使用
			if (message.thumbnailUrl) {
				return message.thumbnailUrl;
			}
			// 默认使用视频文件的第一帧（实际应用中可能需要后端生成缩略图）
			return '/static/images/video-thumbnail.png';
		},

		// 格式化视频时长
		formatVideoDuration(duration) {
			if (!duration || duration <= 0) return '00:00';
			
			const minutes = Math.floor(duration / 60);
			const seconds = Math.floor(duration % 60);
			return `${minutes.toString().padStart(2, '0')}:${seconds.toString().padStart(2, '0')}`;
		},

		// 获取视频缩略图
		getVideoThumbnail(message) {
			// 如果有缩略图URL，优先使用
			if (message.thumbnailUrl) {
				return message.thumbnailUrl;
			}
			// 默认使用视频文件的第一帧（实际应用中可能需要后端生成缩略图）
			return '/static/images/video-thumbnail.png';
		},

		// 格式化视频时长
		formatVideoDuration(duration) {
			if (!duration || duration <= 0) return '00:00';
			
			const minutes = Math.floor(duration / 60);
			const seconds = Math.floor(duration % 60);
			return `${minutes.toString().padStart(2, '0')}:${seconds.toString().padStart(2, '0')}`;
		},

		// 获取视频缩略图
		getVideoThumbnail(message) {
			// 如果有缩略图URL，优先使用
			if (message.thumbnailUrl) {
				return message.thumbnailUrl;
			}
			// 默认使用视频文件的第一帧（实际应用中可能需要后端生成缩略图）
			return '/static/images/video-thumbnail.png';
		},

		// 格式化视频时长
		formatVideoDuration(duration) {
			if (!duration || duration <= 0) return '00:00';
			
			const minutes = Math.floor(duration / 60);
			const seconds = Math.floor(duration % 60);
			return `${minutes.toString().padStart(2, '0')}:${seconds.toString().padStart(2, '0')}`;
		},

		// 获取视频缩略图
		getVideoThumbnail(message) {
			// 如果有缩略图URL，优先使用
			if (message.thumbnailUrl) {
				return message.thumbnailUrl;
			}
			// 默认使用视频文件的第一帧（实际应用中可能需要后端生成缩略图）
			return '/static/images/video-thumbnail.png';
		},

		// 格式化视频时长
		formatVideoDuration(duration) {
			if (!duration || duration <= 0) return '00:00';
			
			const minutes = Math.floor(duration / 60);
			const seconds = Math.floor(duration % 60);
			return `${minutes.toString().padStart(2, '0')}:${seconds.toString().padStart(2, '0')}`;
		},

		// 播放视频（使用自定义视频播放组件）
		playVideo(videoUrl) {
			if (!videoUrl) return;
			
			// 设置当前视频URL并显示播放器
			this.currentVideoUrl = videoUrl;
			this.showVideoPlayer = true;
		},
		
		// 视频播放器关闭事件
		onVideoClose() {
			this.showVideoPlayer = false;
			this.currentVideoUrl = '';
		},

		// 格式化TIM消息
		formatMessage(message) {
			const isSelf = message.from === TIMManager.currentUserId;

			// 处理图片消息
			if (message.type === 'TIMImageElem') {
				const imageInfo = message.payload.imageInfoArray[0];
				return {
					id: message.ID,
					content: '[图片]',
					imageUrl: imageInfo ? imageInfo.url : '',
					type: 'image',
					isSelf: isSelf,
					avatar: isSelf ? '/static/images/avatar/2.jpg' : '/static/images/avatar/1.jpg',
					status: 'success',
					time: new Date(message.time * 1000)
				};
			}

			// 处理视频消息
			if (message.type === 'TIMVideoElem') {
				const videoInfo = message.payload.videoInfo;
				return {
					id: message.ID,
					content: '[视频]',
					videoUrl: videoInfo ? videoInfo.url : '',
					type: 'video',
					isSelf: isSelf,
					avatar: isSelf ? '/static/images/avatar/2.jpg' : '/static/images/avatar/1.jpg',
					status: 'success',
					time: new Date(message.time * 1000)
				};
			}

			// 处理文本消息
			return {
				id: message.ID,
				content: message.payload.text || '',
				type: 'text',
				isSelf: isSelf,
				avatar: isSelf ? '/static/images/avatar/2.jpg' : '/static/images/avatar/1.jpg',
				status: 'success',
				time: new Date(message.time * 1000)
			};
		}
	}
}
</script>

<style lang="scss">
/* #ifdef APP-PLUS */
@import "../../static/colorui/main.css";
@import "../../static/colorui/icon.css";
@import "../../static/zaiui/style/app.scss";
/* #endif */
@import "../../static/zaiui/style/chat.scss";
</style>
